package com.jxb.demo.im.server;

import com.jxb.demo.im.MsgPackDecoder;
import com.jxb.demo.im.MsgPackEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;

public class IMServer {

    public void start(String host,int port){
        //1 创建eventLoopGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //2 创建server的终端
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //3 设置服务端
        serverBootstrap.group(bossGroup,workerGroup)//绑定线程组
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,100)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        //获取channelPipeline
                        ChannelPipeline pipeline = channel.pipeline();
                        //服务端的读空闲检测
                        pipeline.addLast(new IdleStateHandler(5,0,0));
                        //消息解码器
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(65532,0,2,0,2));
                        //解码器
                        pipeline.addLast(new MsgPackDecoder());
                        pipeline.addLast(new LengthFieldPrepender(2));//编码消息体长度;
                        pipeline.addLast(new MsgPackEncoder());
                        pipeline.addLast(new IMServerHeartBeatHandler());//心跳处理
                        pipeline.addLast(new IMServerHandler());//服务端处理
                    }
                });
        try{
            //绑定端口，启动
            ChannelFuture channelFuture = serverBootstrap.bind(host,port).sync();
            channelFuture.channel().closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new IMServer().start("127.0.0.1",8080);
    }

}
